package com.agile.leetcode.redenvelope;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Random;

/**
 * 算法四就是微信红包目前所采用的的算法（大致思路，代码模拟），二倍均值计算公式：2 * 剩余金额/剩余红包数。
 *
 * @Author:ChenZhangKun
 * @Date: 2022/1/24 16:43
 */
public class FourthFunction {
    private static void testPocket4(BigDecimal amount, BigDecimal min, BigDecimal num) {
        BigDecimal remain = amount.subtract(min.multiply(num));
        final Random random = new Random();
        final BigDecimal hundred = new BigDecimal("100");
        final BigDecimal two = new BigDecimal("2");
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal redpeck;
        for (int i = 0; i < num.intValue(); i++) {
            final int nextInt = random.nextInt(100);
            if (i == num.intValue() - 1) {
                redpeck = remain;
            } else {
                redpeck = new BigDecimal(nextInt).multiply(remain.multiply(two).divide(num.subtract(new BigDecimal(i)), 2, RoundingMode.CEILING)).divide(hundred, 2, RoundingMode.FLOOR);
            }
            if (remain.compareTo(redpeck) > 0) {
                remain = remain.subtract(redpeck).setScale(2, BigDecimal.ROUND_HALF_UP);
            } else {
                remain = BigDecimal.ZERO;
            }
            sum = sum.add(min.add(redpeck)).setScale(2, BigDecimal.ROUND_HALF_UP);
            System.out.println("第" + (i + 1) + "个人抢到红包金额为：" + min.add(redpeck));
        }
        System.out.println("红包总额：" + sum);

    }

    public static void main(String[] args) {
        BigDecimal amount = new BigDecimal(100).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal min = new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal num = new BigDecimal(10).setScale(2, BigDecimal.ROUND_HALF_UP);
        testPocket4(amount, min, num);
    }
}
